package com.oauth2.testoauth2.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oauth2.testoauth2.form.WeiboToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/auth")
@CrossOrigin
public class Oauth2Login {

    @Autowired
    private RestTemplate restTemplate;

    private final String CLIENT_ID = "4268990700";
    private final String CLIENT_SECRET = "ab194906ace33fcb1b3e26ad5c68c0cf";
    private final String GRANT_TYPE = "authorization_code";
    private final String REDIRECT_URI = "http://www.wcx.com:8080/success";

    @PostMapping("/weiboLogin")
    public Object success(String code) {
        System.out.println(code);
        JSONObject json = new JSONObject();
        String resp =
                restTemplate.postForObject("https://api.weibo.com/oauth2/access_token?client_id=4268990700&client_secret=ab194906ace33fcb1b3e26ad5c68c0cf&grant_type=authorization_code&redirect_uri=http://blog.com/oauth2&code=" + code, json, String.class);
        System.out.println(resp);
        WeiboToken weiboToken = JSON.parseObject(resp, WeiboToken.class);
        String token = weiboToken.getAccess_token();
        String uid = weiboToken.getUid();
        Map forObject = restTemplate.getForObject("https://api.weibo.com/2/users/show.json?access_token=" + token + "&uid=" + uid, Map.class);
        JSONObject weiboInfoJson = new JSONObject(forObject);
        System.out.println(weiboInfoJson);
        return weiboInfoJson;
    }

}
